package com.link.kingdee.k3cloud.service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import com.link.kingdee.k3cloud.ApiService;
import com.link.kingdee.k3cloud.domain.Authentication;
import com.link.kingdee.k3cloud.domain.RequestParameter;
import com.link.kingdee.k3cloud.domain.RequestService;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author dong.tang
 *
 * @param <P>
 * @param <R>
 */
@Slf4j
public abstract class CommonService<P> implements ApiService<P, String> {

	private static final String COOKIES_KINGDEE_K3CLOUD_WEB = "kingdee-k3cloud-web-cookies";

	private static final Map<String, String> COOKIES = new ConcurrentHashMap<>(4);

	private static final RestTemplate REST_TEMPLATE = new RestTemplate();

	@Setter
	@Getter
	private String endPoint;

	@Setter
	@Getter
	private Authentication auth;
	
	@Override
	public String execute(List<P> params) {
		// 登录认证
		auth();
		// 处理请求
		ResponseEntity<String> re = handleRequest(getService(), params);
		String r = re.getBody();
		// cookies失效后重新登录
		if (r.toString().contains("重新登录")) {
			COOKIES.clear();
			auth();
			re = handleRequest(getService(), params);
			r = re.getBody();
		}
		return r;
	}

	@SuppressWarnings("unchecked")
	private void auth() {
		if (!COOKIES.isEmpty()) {
			return;
		}
		ResponseEntity<String> re = handleRequest(RequestService.SERVICE_AUTH, (List<P>) auth.toReqParamList());
		HttpHeaders headers = re.getHeaders();
		if (headers == null || headers.isEmpty()) {
			throw new RuntimeException("auth of kingdee's header is null");
		}
		setCookies(headers);
	}

	private ResponseEntity<String> handleRequest(RequestService reqService, List<P> params) {
		RequestParameter<P> reqParam = new RequestParameter<>();
		reqParam.setParameters(params);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		headers.set("Cookie", COOKIES.get(COOKIES_KINGDEE_K3CLOUD_WEB));
		HttpEntity<String> httpEntity = new HttpEntity<>(reqParam.toString(), headers);
		log.info("金蝶[{}]请求开始............", reqService.getComment());
		log.info("  请求路径：{}{}", getEndPoint(), reqService.getName());
		log.info("  请求参数：{}", reqParam);
		ResponseEntity<String> responseEntity = REST_TEMPLATE.postForEntity(getEndPoint() + reqService.getName(), httpEntity, String.class);
		log.info("  请求结果：{}", responseEntity.getBody());
		log.info("金蝶[{}]请求结束............", reqService.getComment());
		return responseEntity;
	}

	private void setCookies(HttpHeaders headers) {
		List<String> cookies = headers.get("Set-Cookie");
		log.info("kingdee k3cloud web cookie：{}", cookies);
		if (CollectionUtils.isEmpty(cookies)) {
			throw new RuntimeException("auth of kingdee's k3cloud web cookie is null");
		}
		StringBuilder sb = new StringBuilder();
		cookies.forEach(cookie -> {
			String[] items = cookie.split(";", -1);
//	        String[] nameValuePair = items[0].split("=", 2);
			sb.append(items[0]).append(";");
		});
		COOKIES.put(COOKIES_KINGDEE_K3CLOUD_WEB, sb.toString());
	}
	
}
